/**
 * GET请求封装
 */
function get(url, data = {}) {
  return request(url, data, 'GET')
}

/**
 * POST请求封装
 */
function post(url, data = {}) {
  return request(url, data, 'POST')
}

function request(url, data = {}, method = "GET") {
  var contentType = 'application/json'
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': contentType,
        'Authorization': wx.getStorageSync('easy_schedule_token')
      },
      success: function (res) {
       // console.log(res)
        if (res.statusCode == 200) {
          if (res.data.code == 0) {
            resolve(res.data.data);
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            });
          }

        } else if (res.statusCode == 401) {
          reject("登录已过期")
          wx.showModal({
            title: '提示',
            content: '登录已过期，请立即登录，否则无法正常使用',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.navigateTo({
                  url: '/pages/login/login?toPageUrl=401',
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        } else {
          //请求失败
          reject(res)
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

module.exports = {
  request,
  get,
  post
}